package com.atguigu.flink.chapter05.sink;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/9/15 11:06
 */
public class Flink01_Sink_Kafka_2 {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
    
        DataStreamSource<WaterSensor> s1 = env.fromElements(
            new WaterSensor("sensor_1", 1L, 10),
            new WaterSensor("sensor_1", 2L, 20),
            new WaterSensor("sensor_1", 5L, 20),
            new WaterSensor("sensor_2", 3L, 30),
            new WaterSensor("sensor_1", 4L, 40)
        );
    
        Properties props = new Properties();
        props.setProperty("bootstrap.servers", "hadoop162:9092");
        
        s1
            
            .addSink(
                new FlinkKafkaProducer<WaterSensor>(
                    "default",
                    new KafkaSerializationSchema<WaterSensor>() {
                        @Override
                        public ProducerRecord<byte[], byte[]> serialize(WaterSensor ws,
                                                                        @Nullable Long timestamp) {
                            return new ProducerRecord<>("s1", ws.toString().getBytes(StandardCharsets.UTF_8));
                        }
                    },
                    props,
                    FlinkKafkaProducer.Semantic.NONE
                )
            );
        
    
        env.execute();
    }
}
